#include <iostream>
#include <unistd.h>
#include <sys/select.h>
#include <sys/fcntl.h>
#include <string.h>

#define ERR_CHECK(val, var, msg) if(val == var){perror(msg); exit(-1);}

using std::cout;
using std::endl;


void fun()
{
    int fdw = open("../data/2.pipe", O_WRONLY);
    cout << "---------" << endl;
    int fdr = open("../data/1.pipe", O_RDONLY);
    ERR_CHECK(fdr, -1, "open");
    ERR_CHECK(fdw, -1, "open");
    int ret = 0;
    char buf[1024];
    fd_set rdset;
    cout << "ser:" << endl;
    while(1){
        FD_ZERO(&rdset);
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(fdr, &rdset);
        ret = select(fdr + 1, &rdset, nullptr, nullptr, 0);
        ERR_CHECK(ret, -1, "select");

        if(FD_ISSET(STDIN_FILENO, &rdset)){
            memset(buf, 0, strlen(buf));

            ret = ::read(STDIN_FILENO, buf, 1024);
            ERR_CHECK(ret, -1, "read");
            if(ret == 0){
                cout << "ser close" << endl;
                break;
            }
            ::write(fdw, buf, strlen(buf));
            cout << "send: " << buf;
        }else if(FD_ISSET(fdr, &rdset)){
            memset(buf, 0, strlen(buf));

            ret = ::read(fdr, buf, 1024);
            ERR_CHECK(ret, -1, "read");
            if(ret == 0){
                cout << "cli disconnect!" << endl;
                break;
            }
            cout << "recv: " << buf;
        }

    }

    close(fdw);
    close(fdr);
}

int main(int args, char *argv[])
{
    fun();
    return 0;
}